<template>
	<my-field :label="data.label">
		<view @click="popup.show = !data.readonly">
			<u-input
				v-model="label"
				:readonly="true"
				suffixIcon="arrow-right"
				:placeholder="data.config.placeholder"
			  ></u-input>
		</view>
		<u-calendar v-if="type == 'date-range'" :show="popup.show" :title="popup.title || '请选择'" mode="range" round="8" :closeOnClickOverlay="true"
			color="#2d58cb" :defaultDate="obj.value" @close="popup.show = false" @confirm="popupConfirm"></u-calendar>
		<u-datetime-picker v-else v-model="result" :title="popup.title || '请选择'" :show="popup.show" :mode="type" confirmColor="#2d58cb"
			:closeOnClickOverlay="true" :minDate="minDate" @confirm="popupConfirm" @cancel="popup.show = false" @close="popup.show = false"></u-datetime-picker>
	</my-field>
</template>
<script>
import MyField from '@/pages_form/components/my-field.vue'
export default {
	components: {MyField},
    props: {
        data: {
            type: Object,
            required: true
        },
        /**
         * datetime
         * date
         * time
         * year-month
         */
        type: {
            type: String,
            default: 'time'
        }
    },
    data(){
        return {
            popup: {
                show: false,
                title: ''
            },
            label: '',
            result: '',
			minDate: this.getMinDate(),
			obj: JSON.parse(JSON.stringify(this.data))
        }
    },
	watch:{
	   obj: {
		   deep: true,
		   handler() {
			   this.$emit('fieldValueChange', this.obj)
		   }
	   }
	},
    mounted(){
        // console.log('datetime: ++++++++++++ ', this.data.config, this.type, " ============= ", this.data.type)
        let dateVal
		if (typeof this.obj.value != 'string') {
			if (this.obj.value.length > 1) {
				dateVal = this.obj.value[0] + ' 至 '+ this.obj.value[this.obj.value.length - 1]
			}else {
				dateVal = this.obj.value[0]
			}
        }else {
			dateVal = this.obj.value
		}
		this.label = dateVal
		this.result = dateVal
    },
    methods:{
        popupConfirm(date){
			switch(this.type) {
				case 'date-range':
					this.obj.value = date
					this.label = date[0] +' 至 '+ date[date.length - 1]
					break
				default:
					let format = this.type == 'datetime'? 'yyyy-0m-0d 0h:0f':(this.type == 'time'? '0h:0f':(this.type == 'year-month'? 'yyyy-0m':'yyyy-0m-0d'))
					this.obj.value = this.$util.getFormatDate(date.value, format)
					this.label = this.obj.value
					this.result = date
					break
			}
			this.popup.show = false
        },
		getMinDate () {
			let df = new this.$dateFormat()
			df.setTime((new Date().getFullYear() - 60) + '-01-01', 'yyyy-0m-0d');
			return df.timestamp
		}
    },
}
</script>
